package com.company.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.nio.charset.Charset;

/**
 * @description: a netty discard server
 * @author: ruoan
 * @date: 2020/12/30 17:36
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //((ByteBuf) msg).release();
        ByteBuf msg1 = (ByteBuf) msg;
        try {
            while (msg1.isReadable()) {
                //System.out.print((char)msg1.readByte());
                ////byte r = msg1.readByte();
                ////String s = String.valueOf(r);
                ////byte[] bytes = s.getBytes();
                ////String str = new String(bytes,Charset.forName("utf-8"));
                ////
                ////System.out.println("xxx--xxx:"+str);
                //System.out.flush();

                ctx.write(msg);
                ctx.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            ReferenceCountUtil.release(msg);
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
